package com.pt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.common.CommonResult;
import com.pt.dto.response.ForumTopicResponse;
import com.pt.dto.response.ForumReplyResponse;
import com.pt.entity.ForumSection;
import com.pt.entity.ForumTopic;
import com.pt.entity.ForumReply;
import com.pt.entity.User;
import com.pt.service.ForumService;
import com.pt.service.UserService;
import com.pt.mapper.ForumReplyLikeMapper;
import com.pt.mapper.ForumTopicLikeMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/forum")
@RequiredArgsConstructor
@Api(tags = "论坛接口")
public class ForumController {
    
    private final ForumService forumService;
    private final UserService userService;
    private final ForumReplyLikeMapper forumReplyLikeMapper;
    private final ForumTopicLikeMapper forumTopicLikeMapper;
    
    @ApiOperation("获取论坛板块列表")
    @GetMapping("/sections")
    public CommonResult<List<ForumSection>> getSections() {
        List<ForumSection> sections = forumService.getAllSections();
        return CommonResult.success(sections);
    }
    
    @ApiOperation("获取板块话题列表")
    @GetMapping("/sections/{sectionId}/topics")
    public CommonResult<IPage<ForumTopicResponse>> getTopicsBySection(
            @ApiParam("板块ID") @PathVariable Integer sectionId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") int size) {
        
        Page<ForumTopic> pageParam = new Page<>(page, size);
        IPage<ForumTopic> topics = forumService.getTopicsBySection(sectionId, pageParam);
        
        // 转换为响应对象
        IPage<ForumTopicResponse> result = topics.convert(this::convertTopicToResponse);
        
        return CommonResult.success(result);
    }
    
    @ApiOperation("获取话题详情")
    @GetMapping("/topics/{topicId}")
    public CommonResult<ForumTopicResponse> getTopicDetail(@ApiParam("话题ID") @PathVariable Long topicId) {
        ForumTopic topic = forumService.getTopicById(topicId);
        if (topic == null || topic.getIsDeleted()) {
            return CommonResult.error("话题不存在");
        }
        
        ForumTopicResponse response = convertTopicToResponse(topic);
        return CommonResult.success(response);
    }
    
    @ApiOperation("获取话题回复列表")
    @GetMapping("/topics/{topicId}/replies")
    public CommonResult<IPage<ForumReplyResponse>> getTopicReplies(
            @ApiParam("话题ID") @PathVariable Long topicId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") int size) {
        
        Page<ForumReply> pageParam = new Page<>(page, size);
        IPage<ForumReply> replies = forumService.getRepliesByTopic(topicId, pageParam);
        
        // 转换为响应对象
        IPage<ForumReplyResponse> result = replies.convert(this::convertReplyToResponse);
        
        return CommonResult.success(result);
    }
    
    @ApiOperation("增加话题查看次数")
    @PostMapping("/topics/{topicId}/view")
    public CommonResult<String> increaseViewCount(@ApiParam("话题ID") @PathVariable Long topicId) {
        forumService.increaseViewCount(topicId);
        return CommonResult.success("查看次数增加成功");
    }
    
    @ApiOperation("发表新主题")
    @PostMapping("/topics")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<ForumTopicResponse> createTopic(@RequestBody ForumTopic topic, HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        // 检查是否是公告板块（假设公告板块的ID为1）
        if (topic.getSectionId() == 1 && user.getUserClass() < 4) {
            return CommonResult.error("只有管理员能发公告！");
        }
        
        topic.setAuthorId(user.getId());
        topic.setCreatedTime(LocalDateTime.now());
        topic.setIsDeleted(false);
        topic.setReplyCount(0);
        topic.setViewCount(0);
        topic.setIsSticky(false);
        topic.setIsLocked(false);
        
        ForumTopic createdTopic = forumService.createTopic(topic);
        ForumTopicResponse response = convertTopicToResponse(createdTopic);
        
        return CommonResult.success(response);
    }
    
    @ApiOperation("回复主题")
    @PostMapping("/topics/{topicId}/replies")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<ForumReplyResponse> replyTopic(
            @ApiParam("主题ID") @PathVariable Long topicId,
            @RequestBody ForumReply reply,
            HttpServletRequest request) {
        
        User user = userService.getCurrentUser();
        
        reply.setTopicId(topicId);
        reply.setAuthorId(user.getId());
        reply.setCreatedTime(LocalDateTime.now());
        reply.setIsDeleted(false);
        
        ForumReply createdReply = forumService.createReply(reply);
        ForumReplyResponse response = convertReplyToResponse(createdReply);
        
        return CommonResult.success(response);
    }
    
    @ApiOperation("点赞回复")
    @PostMapping("/replies/{replyId}/like")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> likeReply(@ApiParam("回复ID") @PathVariable Long replyId) {
        User user = userService.getCurrentUser();
        forumService.likeReply(replyId, user.getId());
        return CommonResult.success("点赞成功");
    }
    
    @ApiOperation("点赞主题")
    @PostMapping("/topics/{topicId}/like")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> likeTopic(@ApiParam("主题ID") @PathVariable Long topicId) {
        User user = userService.getCurrentUser();
        forumService.likeTopic(topicId, user.getId());
        return CommonResult.success("点赞成功");
    }
    
    @ApiOperation("删除主题")
    @DeleteMapping("/topics/{topicId}")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> deleteTopic(@ApiParam("主题ID") @PathVariable Long topicId) {
        User user = userService.getCurrentUser();
        String username = user.getUsername();
        
        // 检查权限：作者或管理员可以删除
        if (!forumService.isTopicAuthor(topicId, username) && user.getUserClass() < 4) {
            return CommonResult.error("没有权限删除此主题");
        }
        
        forumService.deleteTopic(topicId);
        return CommonResult.success("主题删除成功");
    }
    
    @ApiOperation("删除回复")
    @DeleteMapping("/replies/{replyId}")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> deleteReply(@ApiParam("回复ID") @PathVariable Long replyId) {
        User user = userService.getCurrentUser();
        String username = user.getUsername();
        
        // 检查权限：作者或管理员可以删除
        if (!forumService.isReplyAuthor(replyId, username) && user.getUserClass() < 4) {
            return CommonResult.error("没有权限删除此回复");
        }
        
        forumService.deleteReply(replyId);
        return CommonResult.success("回复删除成功");
    }
    
    /**
     * 转换ForumTopic为ForumTopicResponse
     */
    private ForumTopicResponse convertTopicToResponse(ForumTopic topic) {
        ForumTopicResponse response = new ForumTopicResponse();
        response.setId(topic.getId());
        response.setSectionId(topic.getSectionId());
        response.setTitle(topic.getTitle());
        response.setContent(topic.getContent());
        response.setAuthorId(topic.getAuthorId());
        response.setIsSticky(topic.getIsSticky());
        response.setIsLocked(topic.getIsLocked());
        response.setReplyCount(topic.getReplyCount());
        response.setViewCount(topic.getViewCount());
        response.setLikeCount(topic.getLikeCount() != null ? topic.getLikeCount() : 0);
        // 判断当前用户是否点赞
        User user = userService.getCurrentUser();
        if (user != null) {
            boolean liked = forumTopicLikeMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.pt.entity.ForumTopicLike>()
                    .eq("topic_id", topic.getId())
                    .eq("user_id", user.getId())
            ) > 0;
            response.setIsLiked(liked);
        } else {
            response.setIsLiked(false);
        }
        response.setLastReplyId(topic.getLastReplyId());
        response.setLastReplyTime(topic.getLastReplyTime());
        response.setCreatedTime(topic.getCreatedTime());
        response.setCreatedAt(topic.getCreatedTime()); // 前端期望的字段名
        response.setIsDeleted(topic.getIsDeleted());
        
        // 获取主题作者用户名
        User author = userService.getUserById(topic.getAuthorId());
        if (author != null) {
            response.setUsername(author.getUsername());
        }
        
        return response;
    }
    
    /**
     * 转换ForumReply为ForumReplyResponse
     */
    private ForumReplyResponse convertReplyToResponse(ForumReply reply) {
        ForumReplyResponse response = new ForumReplyResponse();
        response.setId(reply.getId());
        response.setTopicId(reply.getTopicId());
        response.setContent(reply.getContent());
        response.setAuthorId(reply.getAuthorId());
        response.setReplyToId(reply.getReplyToId());
        response.setFloor(reply.getFloor());
        response.setCreatedTime(reply.getCreatedTime());
        response.setCreatedAt(reply.getCreatedTime()); // 前端期望的字段名
        response.setIsDeleted(reply.getIsDeleted());
        response.setLikeCount(reply.getLikeCount() != null ? reply.getLikeCount() : 0);
        // 判断当前用户是否点赞
        User user = userService.getCurrentUser();
        if (user != null) {
            boolean liked = forumReplyLikeMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.pt.entity.ForumReplyLike>()
                    .eq("reply_id", reply.getId())
                    .eq("user_id", user.getId())
            ) > 0;
            response.setIsLiked(liked);
        } else {
            response.setIsLiked(false);
        }
        // 获取回复用户名
        User author = userService.getUserById(reply.getAuthorId());
        if (author != null) {
            response.setUsername(author.getUsername());
        }
        
        return response;
    }
} 